package servlet.index;

import com.alibaba.fastjson.JSON;
import pojo.Book;
import pojo.Book2;
import service.ConvertBooksType;
import service.SearchIndexpagere;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/searchclass")
public class SearchClassServlet extends HttpServlet {
    private ConvertBooksType convertBooksType = new ConvertBooksType();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应对象类型
        resp.setContentType("application/json;charset=utf-8");
        // 从请求中获取参数
        String bookType = req.getParameter("bookType"); // 获取图书分类名称
        String pageStr = req.getParameter("page"); // 获取当前页数
        System.out.println(bookType);
        System.out.println(pageStr);
        int page = Integer.parseInt(pageStr); // 将字符串转换为整数
        SearchIndexpagere searchIndexpagere = new SearchIndexpagere();
        List<Book> books = searchIndexpagere.selectClassBook(bookType, page);
        List<Book2> book2s = convertBooksType.parseBooks(books);
        if (books.isEmpty()){
            System.out.println("空");
            Book book = new Book();
            Book2 book2 = convertBooksType.parseBook(book);
            book2.setName("无");
            String jsonString = JSON.toJSONString(book2);
            PrintWriter writer = resp.getWriter();
            writer.write(jsonString);
        }else {
            String jsonString = JSON.toJSONString(book2s);
            PrintWriter writer = resp.getWriter();
            writer.write(jsonString);
        }
//        System.out.println(books.get(0).getImageName());

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
